import { Directive } from "vue";

const handlerMap = new WeakMap<Element, Callback>();

const ob = new ResizeObserver((entries: ResizeObserverEntry[]) => {
    entries.forEach((entry: ResizeObserverEntry) => {
        const { target } = entry;
        const handler = handlerMap.get(target);
        handler &&
            handler({
                // 返回边框盒子的大小
                width: entry.borderBoxSize[0].inlineSize, // inlineSize 是逻辑方向属性
                height: entry.borderBoxSize[0].blockSize
            });
    });
});

type Callback = (borderBoxSize: { width: number; height: number }) => void;

const resize: Directive = {
    mounted(el: HTMLElement, binding: { value: Callback }) {
        handlerMap.set(el, binding.value);
        ob.observe(el);
    },
    unmounted(el: HTMLElement) {
        ob.unobserve(el);
    }
};

export default resize;
